#include "TCcalculator.h"
#include "ui_TCcalculator.h"


TCcalculator::TCcalculator(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TCcalculator),
    networkManager(new QNetworkAccessManager(this)) { // 初始化网络请求管理器
    ui->setupUi(this); // 加载 UI 设计



    // 汇率换算部分  发起汇率获取的网络请求
    // API网址 https://www.tanshuapi.com/market/detail-84
    // 定义一个lambda表达式，用于发起汇率查询的请求
    auto fetchExchangeRate = [this](const QString &fromCurrency, const QString &toCurrency) {
        QString apiKey = "e5f019344909aeebd113b1848d839511"; // API key
        QUrl url(QString("http://api.tanshuapi.com/api/exchange/v1/index"));
        QUrlQuery query;
        query.addQueryItem("key", apiKey);
        query.addQueryItem("from", fromCurrency);
        query.addQueryItem("to", toCurrency);
        query.addQueryItem("money", "1");
        url.setQuery(query);

        QNetworkRequest request(url);
        networkManager->get(request);
    };

    // 分别获取CNY对USD、EUR、JPY、HKD和GBP的汇率
    fetchExchangeRate("CNY", "USD");
    fetchExchangeRate("CNY", "EUR");
    fetchExchangeRate("CNY", "JPY");
    fetchExchangeRate("CNY", "HKD");
    fetchExchangeRate("CNY", "GBP");
    // 处理网络响应
    connect(networkManager, &QNetworkAccessManager::finished, [this](QNetworkReply *reply) {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray response = reply->readAll();
            QJsonObject jsonObj = QJsonDocument::fromJson(response).object().value("data").toObject();
            QString fromCurrency = jsonObj["from"].toString();
            QString toCurrency = jsonObj["to"].toString();
            double exchangeRate = jsonObj["exchange"].toString().toDouble();

            // 根据返回的货币代码更新对应汇率
            if (toCurrency == "USD") {
                usdToCnyRate = 1 / exchangeRate; // API返回的是CNY对USD的汇率，我们需要反转它
            } else if (toCurrency == "EUR") {
                eurToCnyRate = 1 / exchangeRate;
            } else if (toCurrency == "JPY") {
                jpyToCnyRate = 1 / exchangeRate;
            } else if (toCurrency == "HKD") {
                hkdToCnyRate = 1 / exchangeRate;
            } else if (toCurrency == "GBP") {
                gbpToCnyRate = 1 / exchangeRate;
            }

        } else {
            QMessageBox::warning(this, tr("网络错误"), tr("无法获取汇率信息：%1").arg(reply->errorString()));
        }
        reply->deleteLater();
    });

    //时间换算 窗口
    connect(ui->TCpushButtonTime,&QPushButton::clicked,[=](){
        ui->TCstackedWidget->setCurrentIndex(0);
    });

    // 时间换算 设置验证器以确保可以输入浮点数
    QDoubleValidator *validator = new QDoubleValidator(0, 10000000, 2, this);
    validator->setNotation(QDoubleValidator::StandardNotation);
    ui->hoursEdit->setValidator(validator);
    ui->minutesEdit->setValidator(validator);
    ui->secondsEdit->setValidator(validator);

    // 时间换算 使用 lambda 表达式实现 clearButtonTime 按钮的功能
    connect(ui->clearButtonTime, &QPushButton::clicked, [this]() {
        ui->hoursEdit->clear();
        ui->minutesEdit->clear();
        ui->secondsEdit->clear();
    });

    // 时间换算 连接转换按钮的点击信号到槽函数
    connect(ui->convertButtonTime, &QPushButton::clicked, [this](){
        double hours = ui->hoursEdit->text().toDouble();
        double minutes = ui->minutesEdit->text().toDouble();
        double seconds = ui->secondsEdit->text().toDouble();

        if (!ui->hoursEdit->text().isEmpty()) {
            // 用户输入了小时
            minutes = hours * 60;
            seconds = hours * 3600;
        } else if (!ui->minutesEdit->text().isEmpty()) {
            // 用户输入了分钟
            hours = minutes / 60;
            seconds = minutes * 60;
        } else if (!ui->secondsEdit->text().isEmpty()) {
            // 用户输入了秒
            minutes = seconds / 60;
            hours = seconds / 3600;
        }

        // 由于涉及到除法，结果可能包含小数部分，使用浮点数可以保留这部分信息
        ui->hoursEdit->setText(QString::number(hours, 'f', 2)); // 'f' 指定使用定点表示法，2 表示小数点后保留两位
        ui->minutesEdit->setText(QString::number(minutes, 'f', 2));
        ui->secondsEdit->setText(QString::number(seconds, 'f', 2));
    });



    //重量换算 窗口
    connect(ui->TCpushButtonWeigh,&QPushButton::clicked,[=](){
       ui->TCstackedWidget->setCurrentIndex(1);
    });

    // 重量换算 设置验证器以确保可以输入浮点数
    QDoubleValidator *weightValidator = new QDoubleValidator(0, 10000000, 2, this);
    weightValidator->setNotation(QDoubleValidator::StandardNotation);

    // 重量换算 为每个重量单位的 QLineEdit 设置验证器
    ui->tonEdit->setValidator(weightValidator);
    ui->kgEdit->setValidator(weightValidator);
    ui->gEdit->setValidator(weightValidator);
    ui->jinEdit->setValidator(weightValidator);
    ui->poundEdit->setValidator(weightValidator);

    // 重量换算 连接转换按钮的点击信号到 lambda 表达式
    connect(ui->convertButtonWeight, &QPushButton::clicked, [this]() {
        double ton = ui->tonEdit->text().toDouble();
        double kg = ui->kgEdit->text().toDouble();
        double g = ui->gEdit->text().toDouble();
        double jin = ui->jinEdit->text().toDouble();
        double pound = ui->poundEdit->text().toDouble();

        // 检查哪个输入框有值，然后进行换算
        if (!ui->tonEdit->text().isEmpty()) {
            kg = ton * 1000;            // 1吨 = 1000千克
            g = kg * 1000;              // 1千克 = 1000克
            jin = kg * 2;               // 1千克 = 2市斤
            pound = kg * 2.20462;       // 1千克 = 2.20462磅
        } else if (!ui->kgEdit->text().isEmpty()) {
            ton = kg / 1000;            // 反向换算到吨
            g = kg * 1000;              // 同上
            jin = kg * 2;               // 同上
            pound = kg * 2.20462;       // 同上
        } else if (!ui->gEdit->text().isEmpty()) {
            kg = g / 1000;              // 克转千克
            ton = kg / 1000;            // 千克转吨
            jin = kg * 2;               // 千克转市斤
            pound = kg * 2.20462;       // 千克转磅
        } else if (!ui->jinEdit->text().isEmpty()) {
            kg = jin / 2;               // 市斤转千克
            g = kg * 1000;              // 千克转克
            ton = kg / 1000;            // 千克转吨
            pound = kg * 2.20462;       // 千克转磅
        } else if (!ui->poundEdit->text().isEmpty()) {
            kg = pound / 2.20462;       // 磅转千克
            g = kg * 1000;              // 千克转克
            jin = kg * 2;               // 千克转市斤
            ton = kg / 1000;            // 千克转吨
        }

        // 更新 QLineEdit 控件的文本
        ui->tonEdit->setText(QString::number(ton, 'f', 2));
        ui->kgEdit->setText(QString::number(kg, 'f', 2));
        ui->gEdit->setText(QString::number(g, 'f', 2));
        ui->jinEdit->setText(QString::number(jin, 'f', 2));
        ui->poundEdit->setText(QString::number(pound, 'f', 2));
    });

    // 重量换算 使用 lambda 表达式实现 clearButtonWeight 按钮的功能
    connect(ui->clearButtonWeight, &QPushButton::clicked, [this]() {
        ui->tonEdit->clear();
        ui->kgEdit->clear();
        ui->gEdit->clear();
        ui->jinEdit->clear();
        ui->poundEdit->clear();
    });


    //长度换算 窗口
    connect(ui->TCpushButtonLength,&QPushButton::clicked,[=](){
       ui->TCstackedWidget->setCurrentIndex(2);
    });

    // 长度换算 设置验证器以确保可以输入浮点数
    QDoubleValidator *lengthValidator = new QDoubleValidator(0, 10000000, 2, this);
    lengthValidator->setNotation(QDoubleValidator::StandardNotation);

    // 为每个长度单位的 QLineEdit 设置验证器
    ui->kmEdit->setValidator(lengthValidator);
    ui->mEdit->setValidator(lengthValidator);
    ui->mileEdit->setValidator(lengthValidator);
    ui->footEdit->setValidator(lengthValidator);
    ui->chiEdit->setValidator(lengthValidator);

    // 长度换算 连接转换按钮的点击信号到 lambda 表达式
    connect(ui->convertButtonLength, &QPushButton::clicked, [this]() {
        double km = ui->kmEdit->text().toDouble();
        double m = ui->mEdit->text().toDouble();
        double mile = ui->mileEdit->text().toDouble();
        double foot = ui->footEdit->text().toDouble();
        double chi = ui->chiEdit->text().toDouble();

        // 假设用户从千米开始输入
        if (!ui->kmEdit->text().isEmpty()) {
            m = km * 1000;          // 1千米 = 1000米
            mile = km / 1.60934;    // 1千米 ≈ 0.621371英里
            foot = km * 3280.84;    // 1千米 ≈ 3280.84英尺
            chi = m * 3;            // 1米 = 3尺
        }
        // 如果用户从米开始输入
        else if (!ui->mEdit->text().isEmpty()) {
            km = m / 1000;
            mile = m / 1609.34;
            foot = m * 3.28084;
            chi = m * 3;
        }
        // 如果用户从英里开始输入
        else if (!ui->mileEdit->text().isEmpty()) {
            km = mile * 1.60934;
            m = km * 1000;
            foot = mile * 5280;
            chi = m * 3;
        }
        // 如果用户从英尺开始输入
        else if (!ui->footEdit->text().isEmpty()) {
            km = foot / 3280.84;
            m = km * 1000;
            mile = foot / 5280;
            chi = m * 3;
        }
        // 如果用户从尺开始输入
        else if (!ui->chiEdit->text().isEmpty()) {
            m = chi / 3;
            km = m / 1000;
            mile = km / 1.60934;
            foot = km * 3280.84;
        }

        // 更新 QLineEdit 控件的文本
        ui->kmEdit->setText(QString::number(km, 'f', 2));
        ui->mEdit->setText(QString::number(m, 'f', 2));
        ui->mileEdit->setText(QString::number(mile, 'f', 2));
        ui->footEdit->setText(QString::number(foot, 'f', 2));
        ui->chiEdit->setText(QString::number(chi, 'f', 2));
    });

    // 长度换算 使用 lambda 表达式实现 clearButtonLength 按钮的功能
    connect(ui->clearButtonLength, &QPushButton::clicked, [this]() {
        ui->kmEdit->clear();
        ui->mEdit->clear();
        ui->mileEdit->clear();
        ui->footEdit->clear();
        ui->chiEdit->clear();
    });


    //面积换算 窗口
    connect(ui->TCpushButtonArea,&QPushButton::clicked,[=](){
       ui->TCstackedWidget->setCurrentIndex(3);
    });

    // 面积换算 设置验证器以确保可以输入浮点数
    QDoubleValidator *areaValidator = new QDoubleValidator(0, 10000000, 2, this);
    areaValidator->setNotation(QDoubleValidator::StandardNotation);

    // 为每个面积单位的 QLineEdit 设置验证器
    ui->sqKmEdit->setValidator(areaValidator);
    ui->hectareEdit->setValidator(areaValidator);
    ui->sqMEdit->setValidator(areaValidator);
    ui->muEdit->setValidator(areaValidator);
    ui->acreEdit->setValidator(areaValidator);

    // 面积换算 连接转换按钮的点击信号到 lambda 表达式
    connect(ui->convertButtonArea, &QPushButton::clicked, [this]() {
        double sqKm = ui->sqKmEdit->text().toDouble();
        double hectare = ui->hectareEdit->text().toDouble();
        double sqM = ui->sqMEdit->text().toDouble();
        double mu = ui->muEdit->text().toDouble();
        double acre = ui->acreEdit->text().toDouble();

        if (!ui->sqKmEdit->text().isEmpty()) {
            // 用户从平方千米开始输入
            hectare = sqKm * 100;
            sqM = sqKm * 1000000;
            mu = sqKm * 1500;
            acre = sqKm * 247.105;
        } else if (!ui->hectareEdit->text().isEmpty()) {
            // 用户从公顷开始输入
            sqKm = hectare / 100;
            sqM = hectare * 10000;
            mu = hectare * 15;
            acre = hectare * 2.47105;
        } else if (!ui->sqMEdit->text().isEmpty()) {
            // 用户从平方米开始输入
            sqKm = sqM / 1000000;
            hectare = sqM / 10000;
            mu = sqM / 666.666; // 亩和平方米的换算因地区而异，这里假设 1 亩 = 666.666 平方米
            acre = sqM / 4046.86; // 1 英亩 ≈ 4046.86 平方米
        } else if (!ui->muEdit->text().isEmpty()) {
            // 用户从亩开始输入
            sqM = mu * 666.666; // 同上，换算关系可能有所不同
            sqKm = sqM / 1000000;
            hectare = sqM / 10000;
            acre = mu * 0.165; // 1 亩 ≈ 0.165 英亩
        } else if (!ui->acreEdit->text().isEmpty()) {
            // 用户从英亩开始输入
            sqM = acre * 4046.86;
            sqKm = sqM / 1000000;
            hectare = sqM / 10000;
            mu = acre / 0.165; // 使用之前提到的亩和英亩的换算关系
        }
        // 更新 QLineEdit 控件的文本
        ui->sqKmEdit->setText(QString::number(sqKm, 'f', 2));
        ui->hectareEdit->setText(QString::number(hectare, 'f', 2));
        ui->sqMEdit->setText(QString::number(sqM, 'f', 2));
        ui->muEdit->setText(QString::number(mu, 'f', 2));
        ui->acreEdit->setText(QString::number(acre, 'f', 2));
    });

    // 面积换算 使用 lambda 表达式实现 clearButtonArea 按钮的功能
    connect(ui->clearButtonArea, &QPushButton::clicked, [this]() {
        ui->sqKmEdit->clear();
        ui->hectareEdit->clear();
        ui->sqMEdit->clear();
        ui->muEdit->clear();
        ui->acreEdit->clear();
    });

    //温度换算 窗口
    connect(ui->TCpushButtonTemperature,&QPushButton::clicked,[=](){
       ui->TCstackedWidget->setCurrentIndex(4);
    });

    // 温度换算 设置验证器以确保可以输入浮点数，同时确保不能输入绝对零度以下的数 //对摄氏度、华氏度好像不太行？
    QDoubleValidator *celsiusValidator = new QDoubleValidator(-273.15, 100000, 2, this);
    celsiusValidator->setNotation(QDoubleValidator::StandardNotation);
    ui->celsiusEdit->setValidator(celsiusValidator);

    QDoubleValidator *fahrenheitValidator = new QDoubleValidator(-459.67, 100000, 2, this);
    fahrenheitValidator->setNotation(QDoubleValidator::StandardNotation);
    ui->fahrenheitEdit->setValidator(fahrenheitValidator);

    QDoubleValidator *kelvinValidator = new QDoubleValidator(0, 100000, 2, this);
    kelvinValidator->setNotation(QDoubleValidator::StandardNotation);
    ui->kelvinEdit->setValidator(kelvinValidator);


    // 温度换算 连接转换按钮的点击信号到 lambda 表达式
    connect(ui->convertButtonTemp, &QPushButton::clicked, [this]() {
        double celsius = ui->celsiusEdit->text().toDouble();
        double fahrenheit = ui->fahrenheitEdit->text().toDouble();
        double kelvin = ui->kelvinEdit->text().toDouble();

        // 检查温度是否低于绝对零度
        if (celsius < -273.15 || fahrenheit < -459.67 || kelvin < 0) {
            QMessageBox::warning(this, "警告", "温度低于绝对零度，请重新输入");
            return;
        }

        // 假设用户从摄氏度开始输入
        if (!ui->celsiusEdit->text().isEmpty()) {
            fahrenheit = celsius * 9/5 + 32;       // 摄氏度转华氏度
            kelvin = celsius + 273.15;             // 摄氏度转开尔文
        } else if (!ui->fahrenheitEdit->text().isEmpty()) {
            // 用户从华氏度开始输入
            celsius = (fahrenheit - 32) * 5/9;
            kelvin = celsius + 273.15;
        } else if (!ui->kelvinEdit->text().isEmpty()) {
            // 用户从开尔文开始输入
            celsius = kelvin - 273.15;
            fahrenheit = celsius * 9/5 + 32;
        }

        // 更新 QLineEdit 控件的文本
        ui->celsiusEdit->setText(QString::number(celsius, 'f', 2));
        ui->fahrenheitEdit->setText(QString::number(fahrenheit, 'f', 2));
        ui->kelvinEdit->setText(QString::number(kelvin, 'f', 2));
    });


    // 温度换算 使用 lambda 表达式实现 clearButtonTemp 按钮的功能
    connect(ui->clearButtonTemp, &QPushButton::clicked, [this]() {
        ui->celsiusEdit->clear();
        ui->fahrenheitEdit->clear();
        ui->kelvinEdit->clear();
    });



    //体积换算 窗口
    connect(ui->TCpushButtonVolume,&QPushButton::clicked,[=](){
       ui->TCstackedWidget->setCurrentIndex(5);
    });
    // 体积换算 设置验证器以确保可以输入浮点数，最多9位整数和2位小数
    QDoubleValidator *volumeValidator = new QDoubleValidator(0, 999999999, 2, this);
    volumeValidator->setNotation(QDoubleValidator::StandardNotation);  // 使用标准记数法
    ui->cubeMeterEdit->setValidator(volumeValidator);
    ui->cubeDecimeterEdit->setValidator(volumeValidator);
    ui->cubeCentimeterEdit->setValidator(volumeValidator);
    ui->cubeFeetEdit->setValidator(volumeValidator);


    //体积换算 连接转换按钮的点击信号到槽函数
    connect(ui->convertButtonVolume, &QPushButton::clicked, [this](){
        double cubeMeter = ui->cubeMeterEdit->text().toDouble();
            double cubeDecimeter = ui->cubeDecimeterEdit->text().toDouble();
            double cubeCentimeter = ui->cubeCentimeterEdit->text().toDouble();
            double cubeFeet = ui->cubeFeetEdit->text().toDouble();

            if (!ui->cubeMeterEdit->text().isEmpty()) {
                cubeDecimeter = cubeMeter * 1000;
                cubeCentimeter = cubeMeter * 1000000;
                cubeFeet = cubeMeter * 35.3147;
            } else if (!ui->cubeDecimeterEdit->text().isEmpty()) {
                cubeMeter = cubeDecimeter / 1000;
                cubeCentimeter = cubeDecimeter * 1000;
                cubeFeet = cubeMeter * 35.3147;
            } else if (!ui->cubeCentimeterEdit->text().isEmpty()) {
                cubeMeter = cubeCentimeter / 1000000;
                cubeDecimeter = cubeCentimeter / 1000;
                cubeFeet = cubeMeter * 35.3147;
            } else if (!ui->cubeFeetEdit->text().isEmpty()) {
                cubeMeter = cubeFeet / 35.3147;
                cubeDecimeter = cubeMeter * 1000;
                cubeCentimeter = cubeMeter * 1000000;
            }

            ui->cubeMeterEdit->setText(QString::number(cubeMeter, 'f', 3));
            ui->cubeDecimeterEdit->setText(QString::number(cubeDecimeter, 'f', 3));
            ui->cubeCentimeterEdit->setText(QString::number(cubeCentimeter, 'f', 3));
            ui->cubeFeetEdit->setText(QString::number(cubeFeet, 'f', 3));
    });

    //体积换算 使用 lambda 表达式实现清空按钮的功能
    connect(ui->clearButtonVolume, &QPushButton::clicked, [this]() {
        ui->cubeMeterEdit->clear();
        ui->cubeDecimeterEdit->clear();
        ui->cubeCentimeterEdit->clear();
        ui->cubeFeetEdit->clear();
    });


    //速度换算 窗口
    connect(ui->TCpushButtonSpeed,&QPushButton::clicked,[=](){
       ui->TCstackedWidget->setCurrentIndex(6);
    });
    // 速度换算 设置验证器以确保可以输入浮点数，最多9位整数和2位小数
    QDoubleValidator *speedValidator = new QDoubleValidator(0, 999999999, 2, this);
    speedValidator->setNotation(QDoubleValidator::StandardNotation);  // 使用标准记数法
    ui->msEdit->setValidator(speedValidator);
    ui->kmhEdit->setValidator(speedValidator);
    ui->mphEdit->setValidator(speedValidator);
    ui->machEdit->setValidator(speedValidator);

    //速度换算 连接转换按钮的点击信号到槽函数
    connect(ui->convertButtonSpeed, &QPushButton::clicked, [this](){
        double ms = ui->msEdit->text().toDouble();
        double kmh = ui->kmhEdit->text().toDouble();
        double mph = ui->mphEdit->text().toDouble();
        double mach = ui->machEdit->text().toDouble();

        if (!ui->msEdit->text().isEmpty()) {
            kmh = ms * 3.6;
            mph = ms * 2.23694;
            mach = ms / 340.29;
        } else if (!ui->kmhEdit->text().isEmpty()) {
            ms = kmh / 3.6;
            mph = kmh / 1.60934;
            mach = ms / 340.29;
        } else if (!ui->mphEdit->text().isEmpty()) {
            ms = mph / 2.23694;
            kmh = mph * 1.60934;
            mach = ms / 340.29;
        } else if (!ui->machEdit->text().isEmpty()) {
            ms = mach * 340.29;
            kmh = ms * 3.6;
            mph = ms * 2.23694;
        }

        ui->msEdit->setText(QString::number(ms, 'f', 3));
        ui->kmhEdit->setText(QString::number(kmh, 'f', 3));
        ui->mphEdit->setText(QString::number(mph, 'f', 3));
        ui->machEdit->setText(QString::number(mach, 'f', 3));
    });

    //速度换算 使用 lambda 表达式实现清空按钮的功能
    connect(ui->clearButtonSpeed, &QPushButton::clicked, [this]() {
        ui->msEdit->clear();
        ui->kmhEdit->clear();
        ui->mphEdit->clear();
        ui->machEdit->clear();
    });



    //进制换算 窗口
    connect(ui->TCpushButtonBase,&QPushButton::clicked,[=](){
        ui->TCstackedWidget->setCurrentIndex(7);
    });
    //进制换算 设置输入框只能接受合适的字符
    QString binaryRegex = "[01]*"; // 2进制只能包含0和1
    QRegularExpressionValidator *binaryValidator = new QRegularExpressionValidator(QRegularExpression(binaryRegex), this);
    ui->binaryEdit->setValidator(binaryValidator);

    QString octalRegex = "[0-7]*"; // 8进制只能包含0到7的数字
    QRegularExpressionValidator *octalValidator = new QRegularExpressionValidator(QRegularExpression(octalRegex), this);
    ui->octalEdit->setValidator(octalValidator);

    QString decimalRegex = "[0-9]*"; // 10进制只能包含0到9的数字
    QRegularExpressionValidator *decimalValidator = new QRegularExpressionValidator(QRegularExpression(decimalRegex), this);
    ui->decimalEdit->setValidator(decimalValidator);

    QString hexadecimalRegex = "[0-9A-Fa-f]*"; // 16进制只能包含0到9的数字和A到F的字母（不区分大小写）
    QRegularExpressionValidator *hexadecimalValidator = new QRegularExpressionValidator(QRegularExpression(hexadecimalRegex), this);
    ui->hexadecimalEdit->setValidator(hexadecimalValidator);

    //进制换算 连接转换按钮的点击信号到槽函数
    connect(ui->convertButtonBase, &QPushButton::clicked, [this](){
        QString binary = ui->binaryEdit->text();
        QString octal = ui->octalEdit->text();
        QString decimal = ui->decimalEdit->text();
        QString hexadecimal = ui->hexadecimalEdit->text();

        // 根据输入的内容进行转换
        if (!binary.isEmpty()) {
            decimal = QString::number(binary.toInt(nullptr, 2));
            octal = QString::number(binary.toInt(nullptr, 2), 8);
            hexadecimal = QString::number(binary.toInt(nullptr, 2), 16);
        } else if (!octal.isEmpty()) {
            decimal = QString::number(octal.toInt(nullptr, 8));
            binary = QString::number(octal.toInt(nullptr, 8), 2);
            hexadecimal = QString::number(octal.toInt(nullptr, 8), 16);
        } else if (!decimal.isEmpty()) {
            binary = QString::number(decimal.toInt(nullptr, 10), 2);
            octal = QString::number(decimal.toInt(nullptr, 10), 8);
            hexadecimal = QString::number(decimal.toInt(nullptr, 10), 16);
        } else if (!hexadecimal.isEmpty()) {
            decimal = QString::number(hexadecimal.toInt(nullptr, 16));
            binary = QString::number(hexadecimal.toInt(nullptr, 16), 2);
            octal = QString::number(hexadecimal.toInt(nullptr, 16), 8);
        }

        // 更新输入框的内容
        ui->binaryEdit->setText(binary);
        ui->octalEdit->setText(octal);
        ui->decimalEdit->setText(decimal);
        ui->hexadecimalEdit->setText(hexadecimal);
    });

    //进制换算 使用 lambda 表达式实现清空按钮的功能
    connect(ui->clearButtonBase, &QPushButton::clicked, [this]() {
        ui->binaryEdit->clear();
        ui->octalEdit->clear();
        ui->decimalEdit->clear();
        ui->hexadecimalEdit->clear();
    });


    //BMI换算 窗口
    connect(ui->TCpushButtonBMI,&QPushButton::clicked,[=](){
        ui->TCstackedWidget->setCurrentIndex(8);
    });
    //BMI换算 设置身高输入框的验证器，限制为非负数，最多1位小数
    QDoubleValidator* BMIheightValidator = new QDoubleValidator(0, 300, 1, this);
    BMIheightValidator->setNotation(QDoubleValidator::StandardNotation);
    ui->heightEdit->setValidator(BMIheightValidator);

    //BMI换算 设置体重输入框的验证器，限制为非负数，最多1位小数
    QDoubleValidator* BMIweightValidator = new QDoubleValidator(0, 500, 1, this);
    BMIweightValidator->setNotation(QDoubleValidator::StandardNotation);
    ui->weightEdit->setValidator(BMIweightValidator);


    // BMI计算、显示以及身体状况判断
    connect(ui->convertButtonBMI, &QPushButton::clicked, [this]() {
        bool okHeight, okWeight;
        double height = ui->heightEdit->text().toDouble(&okHeight) / 100; // 转换为米
        double weight = ui->weightEdit->text().toDouble(&okWeight);

        if (!okHeight || !okWeight || height <= 0 || weight <= 0) {
            ui->bmiValueLabel->setText("无效输入");
            ui->healthyWeightRangeLabel->setText("");
            ui->bodyConditionLabel->setText("");
            return;
        }

        double bmi = weight / (height * height);
        ui->bmiValueLabel->setText(QString::asprintf("BMI值：%.2f", bmi));

        // 判断身体状况
        QString condition;
        if (bmi >= 28.0) {
            condition = "肥胖";
        } else if (bmi >= 24.0) {
            condition = "超重";
        } else if (bmi >= 18.5) {
            condition = "正常";
        } else {
            condition = "过轻";
        }
        ui->bodyConditionLabel->setText(QString("您的身体状况是：%1").arg(condition));

        // 计算健康体重区间
        double healthyMinWeight = 18.5 * height * height;
        double healthyMaxWeight = 24 * height * height;
        ui->healthyWeightRangeLabel->setText(QString::asprintf("健康体重区间：%.2f~%.2fkg", healthyMinWeight, healthyMaxWeight));
    });
    // 清空按钮的实现
    connect(ui->clearButtonBMI, &QPushButton::clicked, [this]() {
        ui->heightEdit->clear();
        ui->weightEdit->clear();
        ui->bmiValueLabel->setText("BMI值：");
        ui->bodyConditionLabel->setText("您的身体状况是：");
        ui->healthyWeightRangeLabel->setText("健康体重区间：");
    });

    //实时汇率换算 窗口 备注：API调用在本文档起始位置 程序每次运行调用4次
    connect(ui->TCpushButtonCurrency,&QPushButton::clicked,[=](){
        ui->TCstackedWidget->setCurrentIndex(9);
    });

    //实时汇率换算 定义验证器，允许的最小值为0，最大值为1e7，最多两位小数
    QDoubleValidator *validatorCNY = new QDoubleValidator(0, 1e7, 2, this);
    validatorCNY->setNotation(QDoubleValidator::StandardNotation);
    ui->editCNY->setValidator(validatorCNY);

    QDoubleValidator *validatorUSD = new QDoubleValidator(0, 1e7, 2, this);
    validatorUSD->setNotation(QDoubleValidator::StandardNotation);
    ui->editUSD->setValidator(validatorUSD);

    QDoubleValidator *validatorEUR = new QDoubleValidator(0, 1e7, 2, this);
    validatorEUR->setNotation(QDoubleValidator::StandardNotation);
    ui->editEUR->setValidator(validatorEUR);

    QDoubleValidator *validatorJPY = new QDoubleValidator(0, 1e7, 2, this);
    validatorJPY->setNotation(QDoubleValidator::StandardNotation);
    ui->editJPY->setValidator(validatorJPY);

    QDoubleValidator *validatorHKD = new QDoubleValidator(0, 1e7, 2, this);
    validatorHKD->setNotation(QDoubleValidator::StandardNotation);
    ui->editHKD->setValidator(validatorHKD);

    QDoubleValidator *validatorGBP = new QDoubleValidator(0, 1e7, 2, this);
    validatorGBP->setNotation(QDoubleValidator::StandardNotation);
    ui->editGBP->setValidator(validatorGBP);

    //实时汇率换算 获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();

    //实时汇率换算 设置标签文本
    ui->labelRemaining->setText(tr("汇率由探数提供 更新于 %1").arg(currentTime.toString("yyyy-MM-dd hh:mm")));

    //实时汇率换算 “转换”槽函数
    connect(ui->convertButtonCurrency, &QPushButton::clicked, [this]() {
        double cny = 0, usd = 0, eur = 0, jpy = 0, hkd = 0, gbp = 0;

        // 检查哪个输入框有输入，并执行相应的转换
        if (!ui->editCNY->text().isEmpty()) {
            cny = ui->editCNY->text().toDouble();
        }
        if (!ui->editUSD->text().isEmpty()) {
            usd = ui->editUSD->text().toDouble() * usdToCnyRate;
            cny = usd;
        }
        if (!ui->editEUR->text().isEmpty()) {
            eur = ui->editEUR->text().toDouble() * eurToCnyRate;
            cny = eur;
        }
        if (!ui->editJPY->text().isEmpty()) {
            jpy = ui->editJPY->text().toDouble() * jpyToCnyRate;
            cny = jpy;
        }
        if (!ui->editHKD->text().isEmpty()) {
            hkd = ui->editHKD->text().toDouble() * hkdToCnyRate;
            cny = hkd;
        }
        if (!ui->editGBP->text().isEmpty()) {
            gbp = ui->editGBP->text().toDouble() * gbpToCnyRate;
            cny = gbp;
        }

        // 更新所有输入框
        usd = cny / usdToCnyRate;
        eur = cny / eurToCnyRate;
        jpy = cny / jpyToCnyRate;
        hkd = cny / hkdToCnyRate;
        gbp = cny / gbpToCnyRate;

        ui->editCNY->setText(QString::number(cny, 'f', 2));
        ui->editUSD->setText(QString::number(usd, 'f', 2));
        ui->editEUR->setText(QString::number(eur, 'f', 2));
        ui->editJPY->setText(QString::number(jpy, 'f', 2));
        ui->editHKD->setText(QString::number(hkd, 'f', 2));
        ui->editGBP->setText(QString::number(gbp, 'f', 2));

    });
    //实时汇率换算 “清空”槽函数
    connect(ui->clearButtonCurrency, &QPushButton::clicked, [this]() {
        ui->editCNY->clear();
        ui->editUSD->clear();
        ui->editEUR->clear();
        ui->editJPY->clear();
        ui->editHKD->clear();
        ui->editGBP->clear();
    });


    //大写数字换算 窗口
    connect(ui->TCpushButtonChineseNumeral,&QPushButton::clicked,[=](){
        ui->TCstackedWidget->setCurrentIndex(10);
    });

    // 大写数字换算 设置数字输入框的验证器
    QDoubleValidator* ChineseNumeralValidator = new QDoubleValidator(-1e10, 1e10, 2, this);
    ChineseNumeralValidator->setNotation(QDoubleValidator::StandardNotation); // 标准数字表示
    ui->lineEditNumber->setValidator(ChineseNumeralValidator);

    connect(ui->convertButtonChineseNumeral, &QPushButton::clicked, [this]() {
        QString number = ui->lineEditNumber->text();

        // 检查输入的数字
        if (!checkNum(number)) {
            QMessageBox::warning(this, "输入错误", "请输入一个大于0的数");
            return;
        }

        // 四舍五入并处理字符串长度
        QString rounded = roundString(number);

        // 分割、格式化并清理数字
        QString formatted = splitNum(rounded);
        QString cleaned = cleanZero(formatted);

        // 如果最后一个是“元”，在后面增加“整”
        if (cleaned.endsWith("元")) {
            cleaned += "整";
        }

        // 如果第一个是“元”并且后面还有如“壹角”等字，除去开头的“元”
        if (cleaned.startsWith("元") && cleaned.length() > 1) {
            cleaned.remove(0, 1); // 移除开头的“元”
        }

        // 显示结果
        ui->labelChineseNumeral->setText(cleaned);
    });


    connect(ui->clearButtonChineseNumeral, &QPushButton::clicked, [this]() {
        ui->labelChineseNumeral->clear();  // 清空标签内容
        ui->lineEditNumber->clear();       // 清空输入框内容
    });

}


TCcalculator::~TCcalculator() {
    delete ui;
}

bool TCcalculator::checkNum(const QString& s) {
    // 将QString转换为double，并检查其是否大于0
    bool ok;
    double d = s.toDouble(&ok);

    // 只有当转换成功并且数字大于0时，才返回true
    if (ok && d > 0) {
        return true;
    }
    return false;
}

QString TCcalculator::roundString(const QString& s) {
    // 将QString转换为double
    bool ok;
    double d = s.toDouble(&ok);

    if (!ok) {
        QMessageBox::warning(this, "输入错误", "输入的不是有效的数字。");
        return "";
    }

    // 四舍五入到小数点后两位
    QString rounded = QString::number(d, 'f', 2);

    return rounded;
}

QString TCcalculator::formatChinese(int flag, const QString& s) {
    int sLength = s.length();
    // 货币大写形式
    QStringList bigLetter = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    // 货币单位
    QStringList unit = {"元", "拾", "佰", "仟", "万",
                        "拾", "佰", "仟",
                        "亿", "拾", "佰", "仟", "万"};
    QStringList small = {"分", "角"};
    // 用来存放转换后的新字符串
    QString newS = "";

    // 逐位替换为中文大写形式
    for (int i = 0; i < sLength; ++i) {
        int digit = s.at(i).digitValue();  // 获取每一位的数字值
        if (flag == INT_ONLY) {
            // 转换整数部分为中文大写形式（带单位）
            newS += bigLetter[digit] + unit[sLength - i - 1];
        } else if (flag == SMALL_ONLY) {
            // 转换小数部分（带单位）
            newS += bigLetter[digit] + small[sLength - i - 1];
        }
    }
    return newS;
}


QString TCcalculator::splitNum(const QString& s) {
    // 如果传入的是空串则继续返回空串
    if (s.isEmpty()) {
        return "";
    }

    // 截取输入数字的整数部分和小数部分
    int decimalPos = s.indexOf('.');  // 找到小数点的位置
    QString intOnly = (decimalPos == -1) ? s : s.left(decimalPos);
    QString smallOnly = (decimalPos != -1) ? s.mid(decimalPos + 1) : "";

    // 处理整数部分和小数部分
    QString intPart = formatChinese(INT_ONLY, intOnly);
    QString smallPart = formatChinese(SMALL_ONLY, smallOnly);

    // 把转换好了的整数部分和小数部分重新拼凑一个新的字符串
    QString newS = intPart + smallPart;

    return newS;
}

QString TCcalculator::replaceAll(const QString& src, const QString& regex, const QString& replacement) {
    QString result = src;
    result.replace(regex, replacement, Qt::CaseSensitive);
    return result;
}

QString TCcalculator::cleanZero(const QString& s) {
    if (s.isEmpty()) {
        return "";
    }

    QString result = s;

    // 定义正则表达式数组
    QStringList regex1 = {"零仟", "零佰", "零拾"};
    QStringList regex2 = {"零亿", "零万", "零元"};
    QStringList units = {"亿", "万", "元"};
    QStringList regex4 = {"零角", "零分"};

    // 第一轮转换把 "零仟", "零佰", "零拾"等字符串替换成一个"零"
    for (const QString& reg : regex1) {
        result.replace(reg, "零");
    }

    // 去除连续的零
    while (result.contains("零零")) {
        result.replace("零零", "零");
    }

    // 第二轮转换考虑 "零亿", "零万", "零元"等情况
    for (int i = 0; i < regex2.size(); ++i) {
        result.replace(regex2[i], units[i]);
    }

    // 第三轮转换把 "零角", "零分"字符串省略
    for (const QString& reg : regex4) {
        result.replace(reg, "");
    }

    // 当 "万"到"亿"之间全部是"零"的时候，忽略"亿万"单位，只保留一个"亿"
    result.replace("亿万", "亿");

    return result;
}






